package ddbtasktracker.datastore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;

import tasktracker.core.abstraction.TaskDataStoreProvider;

public class MySQLTaskDataStoreProvider implements TaskDataStoreProvider {

	private static final String NAMESPACE = "ddbtasktracker.datastore.";

	SqlSessionTemplate sqlSessionTemplate;

	public MySQLTaskDataStoreProvider(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	@Override
	public void clear(String tracker) {
		sqlSessionTemplate.delete(NAMESPACE + "clear", tracker);
	}

	@Override
	public void storeItem(String tracker, String item, String value) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		paramMap.put("key", "");
		paramMap.put("value", value);
		sqlSessionTemplate.insert(NAMESPACE + "storeItemKey", paramMap);
	}

	@Override
	public String acquireItem(String tracker, String item) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		paramMap.put("key", "");
		return sqlSessionTemplate.selectOne(NAMESPACE + "acquireItemKey", paramMap);
	}

	@Override
	public List<String> listItems(String tracker) {
		return sqlSessionTemplate.selectList(NAMESPACE + "listItems", tracker);
	}

	@Override
	public void removeItem(String tracker, String item) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		sqlSessionTemplate.delete(NAMESPACE + "removeItem", paramMap);
	}

	@Override
	public void storeItemKey(String tracker, String item, String key, String value) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		paramMap.put("key", key);
		paramMap.put("value", value);
		sqlSessionTemplate.insert(NAMESPACE + "storeItemKey", paramMap);
	}

	@Override
	public String acquireItemKey(String tracker, String item, String key) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		paramMap.put("key", key);
		return sqlSessionTemplate.selectOne(NAMESPACE + "acquireItemKey", paramMap);
	}

	@Override
	public List<String> listItemKeys(String tracker, String item) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		return sqlSessionTemplate.selectList(NAMESPACE + "listItemKeys", paramMap);
	}

	@Override
	public void removeItemKey(String tracker, String item, String key) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("tracker", tracker);
		paramMap.put("item", item);
		paramMap.put("key", key);
		sqlSessionTemplate.delete(NAMESPACE + "removeItemKey", paramMap);
	}

}
